<?php

namespace Home\Controller;

class ElfinderController extends BaseController
{

    public function index()
    {
        $breadCrumbs = ['文件管理'];
        $this->assign(compact('breadCrumbs'));
        $this->display();
    }

    public function connect()
    {
        $userId = session('user_id');
        $User = M('User');

        $current = $User->field('id,dir_name')->find($userId);

        $currentRoot = [
            [
                'driver' => 'LocalFileSystem',           // driver for accessing file system (REQUIRED)
                'path' => './Public/files/' . $current['dir_name'] . '/',                 // path to files (REQUIRED)
                'URL' => '/Public/files/' . $current['dir_name'] . '/', // URL to files (REQUIRED)
                //'trashHash'     => 't1_Lw',                     // elFinder's hash of trash folder
                'winHashFix' => DIRECTORY_SEPARATOR !== '/', // to make hash same to Linux one on windows too
                //'uploadDeny'    => array('all'),                // All Mimetypes not allowed to upload
                //'uploadAllow'   => array('image', 'text/plain'),// Mimetype `image` and `text/plain` allowed to upload
                //'uploadOrder'   => array('deny', 'allow'),      // allowed Mimetype `image` and `text/plain` only
                'accessControl' => 'access',                    // disable and hide dot starting files (OPTIONAL)
            ],
        ];

        /*$partner = $User->field('id,dir_name')->where(['partner_id'=>$userId])->select();
        //dump($userId);exit;
        array_push($partner,$current);
        $roots = [];

        foreach($partner as $item){
            $roots[] = [
                'driver'        => 'LocalFileSystem',           // driver for accessing file system (REQUIRED)
                'path'          => './Public/files/'.$item['dir_name'].'/',                 // path to files (REQUIRED)
                'URL'           => '/Public/files/'.$item['dir_name'].'/', // URL to files (REQUIRED)
                //'trashHash'     => 't1_Lw',                     // elFinder's hash of trash folder
                'winHashFix'    => DIRECTORY_SEPARATOR !== '/', // to make hash same to Linux one on windows too
                //'uploadDeny'    => array('all'),                // All Mimetypes not allowed to upload
                //'uploadAllow'   => array('image', 'text/plain'),// Mimetype `image` and `text/plain` allowed to upload
                //'uploadOrder'   => array('deny', 'allow'),      // allowed Mimetype `image` and `text/plain` only
                'accessControl' => 'access',                    // disable and hide dot starting files (OPTIONAL)
            ];
        }*/

        $roots = $this->getUserInfo($userId, $currentRoot);

        //dump($roots);exit;

        $options = array(
            'roots' => $roots
        );

        //dump($options);exit;


        //define("IN_ADMIN",1);//重要，定义一个常量，在插件的PHP入口文件中验证，防止非法访问。
        require './Public/elfinder/php/connector.minimal.php';


    }


    //遍历所有下级用户
    private function getUserInfo($userId, $roots = [])
    {
        $User = M('User');
        $partner = $User->field('id,dir_name')->where(['partner_id' => $userId])->select();


        if ($partner) {
            foreach ($partner as $item) {
                $roots[] = [
                    'dispInlineRegex' => '^(?:image|application/(?:vnd\.)?(?:ms(?:-office|word|-excel|-powerpoint)|openxmlformats-officedocument)|text/plain$)',
                    'driver' => 'LocalFileSystem',           // driver for accessing file system (REQUIRED)
                    'path' => './Public/files/' . $item['dir_name'] . '/',                 // path to files (REQUIRED)
                    'URL' => '/Public/files/' . $item['dir_name'] . '/', // URL to files (REQUIRED)
                    //'trashHash'     => 't1_Lw',                     // elFinder's hash of trash folder
                    'winHashFix' => DIRECTORY_SEPARATOR !== '/', // to make hash same to Linux one on windows too
                    //'uploadDeny'    => array('all'),                // All Mimetypes not allowed to upload
                    //'uploadAllow'   => array('image', 'text/plain'),// Mimetype `image` and `text/plain` allowed to upload
                    //'uploadOrder'   => array('deny', 'allow'),      // allowed Mimetype `image` and `text/plain` only
                    'accessControl' => 'access',                    // disable and hide dot starting files (OPTIONAL)
                ];
                //dump($roots);exit;
                $roots = array_merge($this->getUserInfo($item['id'], $roots));

            }
        }

        return $roots;
    }


    /**
     * 导入模型
     */

    public function addModel()
    {
        $file = I('file', '');
        $fd = I('fd', 0);
        // 添加到数据库
        if (!$fd) $this->error('fd不存在');
        if (!file_exists($file)) $this->error('文件不存在');
        $tag = md5_file($file);
        $ImportModel = M('ImportModel');
        $res = $ImportModel->where(['md5' => $tag])->find();
        if ($res) {
            $ImportModel->where(['md5' => $tag])->save(['status' => 0]);
        } else {
            $ImportModel->add(['md5' => $tag, 'file_path' => $file, 'status' => 0, 'create_time' => time()]);
        }

        curl('http://' . C('SWOOLE_SERVER') . '/singleImport', 'POST', ['fd' => $fd, 'file' => $file, 'tag' => $tag]);
    }

    /**
     * 模型预览和导入入口
     */
    public function importModel()
    {
        $file = I('file', '');
        if (empty($file)) $this->error('获取文件路径失败');

        $filePath = getcwd() . '/Public/files/' . $file;

        if (!file_exists($filePath)) $this->error('文件不存在');

        //判断IFC文件是否已经导入
        $md5 = md5_file($filePath);
        $ImportModel = M('ImportModel');
        $where['md5'] = $md5;
        $res = $ImportModel->where($where)->find();

        if ($res['status'] == 1) {
            header('Location: http://' . C('BIM_SERVER') . '/doc/' . $md5);
            exit;
        } elseif ($res['status'] == 2) {
            $this->error('正在生成预览，请稍后尝试开打');
        }

        if ($res['status'] == 3) {
            $title = '模型预览生成失败！';
            $button = '再试一次';
        } else {
            $title = '模型还未生成预览！';
            $button = '生成预览';
        }

        $this->assign('title', $title);
        $this->assign('button', $button);
        $this->assign(compact('filePath', 'file'));
        $this->display();
    }

    /**
     * 自动导入
     */
    public function autoImport()
    {
        // todo 批量上传错误，只会增加一条记录
        $file = I('files', '');
        if (empty($file)) $this->error('获取文件路径失败');

        $filePath = getcwd() . '/Public/files/' . $file;

        if (!file_exists($filePath)) $this->error('文件不存在');

        //判断IFC文件是否已经导入
        $md5 = md5_file($filePath);
        $ImportModel = M('ImportModel');
        $res = $ImportModel->where(['md5' => $md5])->find();

        if ($res) {
            // 更新路径和时间
            $ImportModel->where(['md5' => $md5])->save(['file_path' => $filePath, 'create_time' => time()]);
        } else {
            $ImportModel->add(['md5' => $md5, 'file_path' => $filePath, 'status' => 0, 'create_time' => time()]);
            curl('http://' . C('SWOOLE_SERVER') . '/autoImport', 'POST');
        }
    }


    public function test()
    {
        curl('http://' . C('SWOOLE_SERVER') . '/autoImport', 'POST');
    }


}